<template>
  <BasicDrawer :width="800" @register="registerDrawer" showFooter @ok="handleConfirm">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { message, Modal } from 'ant-design-vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { menuFormSchemas } from '../menu.data';
  import type { TreeProps } from 'ant-design-vue';
  import type { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
  import { getMenuAllTree, updateMenu } from '/@/api/sys/menu';

  const emit = defineEmits(['success']);

  let recordId = '';

  const [registerForm, { setFieldsValue, validate, updateSchema, resetFields }] = useForm({
    schemas: menuFormSchemas,
    showActionButtonGroup: false,
  });

  const _walk = (
    data: TreeProps['treeData'],
    parent: Nullable<TreeDataItem>,
    callback: (item: TreeDataItem, parent: Nullable<TreeDataItem>) => void
  ) => {
    data?.forEach((item) => {
      callback(item, parent);
      _walk(item.children, item, callback);
    });
  };

  const walk = (data: TreeProps['treeData'], callback: (item: TreeDataItem, parent: Nullable<TreeDataItem>) => void) => {
    _walk(data, null, callback);
  };

  const setParentIdTreeData = async () => {
    const treeData = await getMenuAllTree();
    walk(treeData, (item, parent) => {
      item.value = item.id;
      item.label = item.name;
      if (item.id === recordId || parent?.disabled) {
        item.disabled = true;
      }
    });
    treeData.unshift({
      value: '0',
      label: '无',
      children: [],
    });

    updateSchema({
      field: 'parentId',
      componentProps: {
        treeData,
      },
    });
  };

  const [registerDrawer, { changeLoading, changeOkLoading, closeDrawer }] = useDrawerInner(async (data) => {
    changeLoading(true);
    try {
      recordId = data.record.id;
      await setParentIdTreeData();
      await setFieldsValue(data.record);
    } finally {
      changeLoading(false);
    }
  });

  const handleConfirm = async () => {
    let values = await validate();
    changeOkLoading(true);
    try {
      await updateMenu({
        menuId: recordId,
        ...values,
      });
      message.success('修改系统菜单信息成功');
      emit('success');
      closeDrawer();
    } finally {
      changeOkLoading(false);
    }
  };
</script>
